package com.sky.controller;

import com.sky.constant.MessageConstant;
import com.sky.properties.AliOssProperties;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author 梁科
 * @Version 1.0
 * @ Date 2025/10/20 20:18
 */
@Api(tags = "用于文件上传的通用接口")
@RestController
@RequestMapping(value = "/admin/common")
@Slf4j
public class CommonController {

    @Resource
    private AliOssProperties aliOssProperties;

    /**
     * 文件上传接口
     *
     * @param file 前端传来的文件类型
     * @return
     */
    @PostMapping(value = "/upload")
    @ApiOperation(value = "文件上传")
    public Result<String> upload(MultipartFile file) {
        AliOssUtil aliOssUtil = new AliOssUtil(aliOssProperties.getEndpoint(), aliOssProperties.getAccessKeyId(), aliOssProperties.getAccessKeySecret(), aliOssProperties.getBucketName());
        String originalFilename = file.getOriginalFilename();   // 获取用户上传的文件名
        // 截取文件扩展名eg：.jpg .png等
        String extendName = originalFilename.substring(originalFilename.lastIndexOf("."));
        String aliOssFileName = UUID.randomUUID().toString() + extendName;
        try {
            // 调用aliOssUtil工具类的upload方法，该方法可以返回文件上传到的目标地址/网址
            String aliOssFilePath = aliOssUtil.upload(file.getBytes(), aliOssFileName);
            return Result.success(aliOssFilePath);
        } catch (IOException e) {
            log.error("文件上传失败：{}", e);
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
